/*
 * 
 * 
 */
package Controller.CoreServlet.Ultility;

import Controller.ShowServlet.WelcomeServlet;
import Model.BeanUltility.ResultsetMapper;
import Model.DataUltility.Data_Access;
import Model.ObjectBean.ViewBean.LoginStatus;
import Model.ObjectBean.ViewBean.PersonalInfo_FrDatabase;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
import javax.servlet.*;

/**
 *
 * @author chickencake1
 */
public class SSCookie_Login {
    
    /*Function : Add new cookie to remember logged user in a session until 
     * browser close.
     * 
     * 
     */
    public static void add_ShortTime_Cookies(HttpServletResponse respnose,String cookie_Name
            ,String cookie_Value)
    {
        try {
            Cookie cookie = new Cookie(cookie_Name,URLEncoder.encode(cookie_Value,"UTF-8"));                 
            /*
            * setPath = "/" to specify that this cookie apply to all URL  
            * on this website. 
             */
            cookie.setPath("/");
            respnose.addCookie(cookie);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SSCookie_Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /*Function : Add new cookie in fix time that will save in disk
     * If MaxAge=0 --> cookie will be delete
     */
    public static void add_LongTime_Cookies(HttpServletResponse respnose,String cookie_Name
            ,String cookie_Value,int TimeAge)
    {
        Cookie cookie;                 
        try {
            cookie = new Cookie(cookie_Name,URLEncoder.encode(cookie_Value,"UTF-8"));
        cookie.setPath("/");
        cookie.setMaxAge(TimeAge); 
        respnose.addCookie(cookie);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SSCookie_Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*
        * setPath = "/" to specify that this cookie apply to all URL  
        * on this website. 
         */

    }
    
    /*Function: CheckLogin state
     * choose :0 --> check by Name
     * choose :1 --> check by Value
     */
    public static boolean check_cookieLoginInfo(HttpServletRequest request,int choose,String confirm)
    {
        Cookie [] cookie = request.getCookies();
        if(choose==1)
        {
            for(int i=0;i<cookie.length;i++)
            {
                if(cookie[i].getValue().trim().equals(confirm))
                 return true;
            }
        }
        else if(choose==0)
        {
                for(int i=0;i<cookie.length;i++)
            {
                if(cookie[i].getName().trim().equals(confirm))
                 return true;
            }
        }
        return false;
    }
    
        /*Function: CheckLogin state
     * choose :0 --> check by Name
     * choose :1 --> check by Value
     */
      public static String get_cookieInfo(HttpServletRequest request,String confirm)
    {
        Cookie [] cookie = request.getCookies();

            for(int i=0;i<cookie.length;i++)
            {
                if(cookie[i].getName().trim().equals(confirm))
                {
                try {
                    String value=URLDecoder.decode(cookie[i].getValue(),"UTF-8");
                    return value;
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(SSCookie_Login.class.getName()).log(Level.SEVERE, null, ex);
                }
                }
            }    
        return null;
    }
     public static void CheckandRecover(HttpServletRequest request)
     {
          LoginStatus status = new LoginStatus();
        status.setStatus("false");
        PersonalInfo_FrDatabase perInfo=new PersonalInfo_FrDatabase();
        if(request.getCookies()!=null && SSCookie_Login.check_cookieLoginInfo(request,1,"logged"))
        {
            status.setStatus("true");
            Data_Access access = new Data_Access();
            String [] column={"id","passw"};
            String [] data={SSCookie_Login.get_cookieInfo(request,"username"),
            SSCookie_Login.get_cookieInfo(request,"passw")};
            
            ResultSet rs = access.getInformation("login_account", column, data);
            int count=0;
            try {
                rs.last();
                //perInfo.setFirstname(SSCookie_Login.get_cookieInfo(request,"perInf"));
            } catch (SQLException ex) {
                Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                count=rs.getRow();
            } catch (SQLException ex) {
                Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            if(count==1)
            {
                String column1[]={"id"};
                String data1[]={SSCookie_Login.get_cookieInfo(request,"username")};
                ResultSet rs1 =access.getInformation("personal_info", column1, data1);
                try {
                    ResultsetMapper.mapperResultsettoObject(rs1,PersonalInfo_FrDatabase.class,perInfo);
                } catch (SQLException ex) {
                    Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }            
        }
                 request.getSession().setAttribute("status", status);
         request.getSession().setAttribute("perInfo", perInfo);
     }
}
